import requests
import time
import re
from PIL import Image
import json

# 定义请求头
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36'
}

def get_qrcode():
    image_url = "https://v2.qr.weibo.cn/inf/gen"
    params = {
        'entry': 'o',
        'ize': '180',
        'ervice_id': 'pc_protection',
        'callback': 'tk_' + str(time.time() * 10000)
    }
    response = requests.get(image_url, headers=headers, params=params)
    print(response.text)  # 打印响应内容以便检查
    try:
        # 从响应中提取二维码图片链接和 qrid（用于查询二维码状态）
        api_key = re.search('.*?api_key=(.*)"', response.text).group(1)
        qrid = re.search('.*?"qrid":"(.*)?",', response.text).group(1)
        # 拼接二维码图片的完整 URL
        img_url = 'https://v2.qr.weibo.cn/inf/gen?api_key=' + api_key
        return img_url, qrid
    except AttributeError:
        print("无法从响应中提取所需信息，可能是接口发生变化或响应格式不正确。")
        return None, None

def show_qrcode(img_url, qrid):
    """
    保存并显示二维码
    """
    response = requests.get(img_url, headers=headers)
    # 将二维码图片保存到本地
    with open('img.jpg', 'wb') as f:
        f.write(response.content)
        f.close()
    try:
        # 显示二维码图片
        img = Image.open('img.jpg')
        img.show()
    except Exception as e:
        print(u"请到当前目录下，找到二维码并扫描", e)

def check_qrcode_status(qrid):
    """
    轮询查询二维码状态
    """
    check_url = 'https://login.sina.com.cn/sso/qrcode/check?entry=sso&qrid={}&callback=stk_{}'
    while True:
        response = requests.get(check_url.format(qrid, str(time.time() * 100000)), headers=headers)
        data = re.search('.*?\((.*)\)', response.text).group(1)
        data_js = json.loads(data)
        # 根据返回的状态码判断二维码状态
        if '50114001' in str(data_js['retcode']):
            print('二维码未使用，请扫码！')
        elif '50114002' in str(data_js['retcode']):
            print('已扫码，请点击确认登录！')
        elif '20000000' in str(data_js['retcode']):
            print('登录成功！')
            break
        elif '50114004' in str(data_js['retcode']):
            print('该二维码已失效，请重新运行程序！')
        else:
            print('其他情况', str(data_js['retcode']))
        time.sleep(1)


if __name__ == "__main__":
    img_url, qrid = get_qrcode()
    show_qrcode(img_url, qrid)
    check_qrcode_status(qrid)